import datetime
import time
from multiprocessing import Process

import psutil

from Spider.close20 import update_stack_close20
from Spider.config import CONFIG, G
from Spider.convbond import run as run_convbond
# from Spider.fund import run as run_fund
from Spider.fund import run as run_fund
from Spider.stack import run as run_stack
from Spider.wechat import WeChatManager

# 全局变量
wechat_manager = WeChatManager(libs_path='libs')


def msg_consumer(MESSAGE_QUEUE):
    """
    消息队列消费者

    :param q:
    :return:
    """

    def check_wechat(exe_name='WeChat.exe'):
        pids = psutil.process_iter()
        for pid_temp in pids:
            pid_dic = pid_temp.as_dict(attrs=['pid', 'name'])
            if pid_dic['name'] == exe_name:
                return
        raise Exception("微信未启动")

    check_wechat()
    time.sleep(0.5)
    wechat_manager.manager_wechat(smart=True)
    while True:
        if not MESSAGE_QUEUE.empty():
            message = MESSAGE_QUEUE.get()
            for wxid in CONFIG.WXID_LIST:
                wechat_manager.send_text(1, wxid,
                                         '{}  {}'.format(message, datetime.datetime.now().strftime('%H:%M:%S')))


def main():
    cu = Process(target=msg_consumer, args=(G.MESSAGE_QUEUE,))
    G.MESSAGE_QUEUE.put("微信连接成功，测试信息")
    cu.start()
    print("更新前{}天平均".format(-CONFIG.LAST_N_DAY_MEAN))
    update_stack_close20()
    pr_convbond = Process(target=run_convbond, args=(G.MESSAGE_QUEUE,))
    pr_fund = Process(target=run_fund, args=(G.MESSAGE_QUEUE,))
    pr_stack = Process(target=run_stack, args=(G.MESSAGE_QUEUE,))

    pr_convbond.start()
    pr_fund.start()
    pr_stack.start()

    while True:
        time.sleep(1)


if __name__ == '__main__':
    main()
